#! -*-coding:utf-8 -*-
import os
from flask import Flask
from flask_script import Manager,Server
from flask_migrate import MigrateCommand
from .models import *
from settings import real_env
from .utils import load_log
from .extentions import load_extions
from .middlewares import load_middlewares
from .errorhandlers import load_errorhandlers
from .blueprints import load_blueprints


def create_app():
    #避免报错,先尝试创建日志文件夹
    try:
        os.mkdir(real_env.LOG_DIR_NAME)
    except Exception as e:
        pass
    load_log()
    app = Flask(__name__)
    app.config.from_object(real_env)
    load_extions(app=app)
    load_blueprints(app=app)
    load_middlewares(app=app)
    load_errorhandlers(app=app)
    server = Server(
        host=real_env.HOST,
        port=real_env.PORT,
        use_debugger=real_env.DEBUG,
        use_reloader=real_env.RELOAD
    )
    manager = Manager(app=app)
    manager.add_command('db', MigrateCommand)
    manager.add_command('start', server)

    return manager
